package com.xpsoft.oa.service.produce.impl;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.reflect.TypeToken;
import com.xpsoft.core.service.impl.BaseServiceImpl;
import com.xpsoft.core.util.JsonUtil;
import com.xpsoft.oa.dao.produce.MaterialAllocationDao;
import com.xpsoft.oa.dao.produce.MaterialAllocationInfoDao;
import com.xpsoft.oa.model.produce.MaterialAllocation;
import com.xpsoft.oa.model.produce.MaterialAllocationInfo;
import com.xpsoft.oa.service.produce.MaterialAllocationService;

public class MaterialAllocationServiceImpl extends BaseServiceImpl<MaterialAllocation> implements MaterialAllocationService{
	private MaterialAllocationDao dao;
	@Autowired
	private MaterialAllocationInfoDao materialAllocationInfoDao;
	public MaterialAllocationServiceImpl(MaterialAllocationDao dao) {
		super(dao);
		this.dao=dao;
	}

	@Override
	public void saveMaterialAllocation(MaterialAllocation materialAllocation,
			String dataList) {
		// TODO Auto-generated method stub
		dao.save(materialAllocation);
		Boolean isNew = true;//新增标志
		if(materialAllocation.getId()!=null){
			isNew = false;
		}
		dao.save(materialAllocation);
		if(StringUtils.isNotBlank(dataList)){
			List<MaterialAllocationInfo> materialAllocationInfoList = JsonUtil.fromJsonTypes(dataList,
					new TypeToken<List<MaterialAllocationInfo>>() {
					}.getType());
			if(!isNew){//修改
				List<Long> idList = new ArrayList<Long>();
				for(MaterialAllocationInfo materialAllocationInfo:materialAllocationInfoList){
					if(materialAllocationInfo.getId()!=null){//修改的记录
						idList.add(materialAllocationInfo.getId());
					}
				}
				if(idList.size()>0){//先进行删除
					materialAllocationInfoDao.deleteMaterialAllocationInfos(materialAllocation.getId(), idList);
				}
			}
			for(MaterialAllocationInfo materialAllocationInfo:materialAllocationInfoList){
				materialAllocationInfo.setMaterialAllocation(materialAllocation);
				materialAllocationInfoDao.save(materialAllocationInfo);
			}
		}
	}

	
}